<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>
    <el-tree
      style="margin: 20px 0"
      ref="treeRef"
      :data="treeInfo"
      node-key="id"
      show-checkbox
      default-expand-all
      :props="defaultProps"
    />
    <el-button size="small" type="primary" @click="save">保存</el-button>
    <el-button size="small" @click="cancel">取消</el-button>
  </div>
</template>

<script>
import { setRole, getAllRole } from "@/api/acl/person/index";
export default {
  data() {
    return {
      treeInfo: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      roleId: this.$route.query.id,
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getCheckedIds(auths, initArr = []) {
      auths.forEach((item) => {
        if (item.select && item.level === 4) {
          initArr.push(item.id);
        } else if (item.children) {
          this.getCheckedIds(item.children, initArr);
        }
      });
      return initArr;
    },
    async getData() {
      const result = await getAllRole(this.roleId);
      this.treeInfo = result.data.children;
      const checkedIds = this.getCheckedIds(this.treeInfo);
      this.$refs.treeRef.setCheckedKeys(checkedIds);
    },
    // 保存
    async save() {
      const checkedIds = this.$refs.treeRef.getCheckedKeys();
      const CheckedIds = this.$refs.treeRef.getHalfCheckedKeys();
      var ids = checkedIds.concat(CheckedIds).join(",");
      await setRole(this.$route.query.id, ids);
      this.$message.success("分配权限成功");
      this.$router.replace("/acl/person");
    },
    // 取消
    cancel() {
      this.$router.replace("/acl/person");
    },
  },
};
</script>

<style></style>
